package com.cc.demo.listener;

import com.cc.demo.annotation.TransactionalMessage;
import com.cc.demo.channel.ConsumerChannel;
import com.cc.demo.dto.TransactionMessage;
import com.cc.demo.entity.Inventory;
import com.cc.demo.mesage.service.MessageService;
import com.cc.demo.service.InventoryService;
import com.cc.demo.utils.UuidGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class ConsumerListener {

    private final InventoryService inventoryService;

    private final MessageService messageService;

    @Autowired
    @Qualifier(ConsumerChannel.TRANSACTION_COMPLETED)
    private MessageChannel completed;

    @Autowired
    @Qualifier(ConsumerChannel.TRANSACTION_FAILED)
    private MessageChannel failed;

    @StreamListener(ConsumerChannel.INPUT)
    @TransactionalMessage
    public void receivedMessage(Message<TransactionMessage<?>> message) {
        // 接收message
        // TODO 需要做幂等性校验,如果重复，ACK处理成功.=> AOP处理？
        TransactionMessage<?> transactionMessage = message.getPayload();
        String orderId = transactionMessage.getBusinessKey();
        Inventory inventory = Inventory.builder().orderId(orderId).inventoryId(UuidGenerator.newUuid()).build();
        //业务操作
        inventoryService.addInventory(inventory);
    }
}
